<?php

namespace app\index\controller;

use app\index\job\JobActivity;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;
use uploadImg\imgcompress;

/**
 * 立早官网小程序接口
 * */
class Api extends Controller
{
    public function codeGetOpenidToUserInfo()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, 'code缺失');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $user_data = json_decode(file_get_contents($url));

        $openid = $user_data->openid;

        $user_info = Db::name('user')->field('id,username,avatar')->where(['openid' => $openid])->find();
        if ($user_info) {
            $user_info['avatar'] = $user_info['avatar'] ? doAvatar($user_info['avatar']) : '/images/avatar.png';

            apiReturn(1, '获取用户信息成功', $user_info);
        } else {
            apiReturn(2, '获取用户信息失败');
        }
    }

    /**
     * 微信登录
     * */
    public function wxLogin()
    {
        $input = Request()->param();

        $code = $input['code'];
        $username = $input['username'] ? : '微信用户';
        $avatar = $input['avatar'] ? : 0;

        if (empty($code)) apiReturn(2, 'CODE缺失');
        if (empty($username)) apiReturn(2, '用户昵称缺失');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $user_data = json_decode(file_get_contents($url));

        $openid = $user_data->openid;

        if (empty($openid)) apiReturn(2, 'openid获取失败');

        $info = Db::name('user')->where(['openid' => $openid])->find();
        if ($info['status'] == 2) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (!$info) {
            // 新用户
            $save_data = [
                'username' => $username,
                'avatar' => $avatar,
                'openid' => $openid,
                'create_time' => time()
            ];

            $id = Db::name('user')->insertGetId($save_data);
        } else {
            $save_data = [
                'username' => $username,
                'avatar' => $avatar,
            ];
            Db::name('user')->where(['id' => $info['id']])->update($save_data);

            // 老用户
            $id = $info['id'];
        }

        if ($id) {
            $avatar = Db::name('user')->where(['id' => $id])->value('avatar');
            $avatar = $avatar ? doAvatar($avatar) : '/images/avatar.png';

            $data = [
                'id' => $id,
                'openid' => $openid,
                'avatar' => $avatar
            ];

            apiReturn(1, '登录成功', $data);
        } else {
            apiReturn(2, '登录失败');
        }
    }

    public function bannnerList()
    {
        $list = Db::name('banner')->field('id,img')->order('id asc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * @param $url
     * @param $data
     * @return mixed|false
     */
    public function httpCurl($url, $data = null, $header = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        // 设置连接超时时间（单位：秒）
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60); // 60 秒
        // 设置请求超时时间（单位：秒）
        curl_setopt($curl, CURLOPT_TIMEOUT, 120);       // 120 秒
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        // 设置header头
        if (!empty($header)) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($curl);
        if ($response === false) {
            // 处理 CURL 请求失败的情况
            echo 'CURL Error: ' . curl_error($curl);
            return false;
        } else {
            // 请求成功，返回 API 响应数据
            return $response;
        }

        curl_close($curl);
    }


    private $api_key = 'sk-23079ec95fee433e8c0d09c0610ae7f4';

    public function getHistoryMessages()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $type = $input['type'] ? : 1;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        switch ($type) {
            case 1:
                $default_prompt = '我是小红书文案助手，你有什么文案需要我帮你写吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 2:
                $default_prompt = '我可以帮你进行诗词创作，你有什么想法吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 3:
                $default_prompt = '将你需要扩写的句子发给我，我可以帮你进行扩写哦';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 4:
                $default_prompt = '我可以帮你生成标题';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 5:
                $default_prompt = '我可以帮你撰写营销文案，你有什么想法吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 6:
                $default_prompt = '我可以帮你进行朋友圈文案创作，你有什么想法吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 7:
                $default_prompt = '我可以帮你制作方案，你有什么想法吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 8:
                $default_prompt = '我是直播带货剧本生成器，你可以输入你的商品信息，我会帮你生成一段直播带货的剧本。';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 9:
                $default_prompt = '我是短视频脚本生成器，你可以输入你的视频内容，我会帮你生成一段短视频的脚本。';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
        }

        $list = Db::name('message')->field('id,prompt,text')->where(['user_id' => $user_id, 'type' => $type])->order('id asc')->select();
        $history_messages = [];
        if ($list) {
            foreach ($list as &$v) {
                $history_messages[] = [
                    'role' => 'user',
                    'content' => $v['prompt']
                ];
                $history_messages[] = [
                    'role' => 'assistant',
                    'content' => $v['text']
                ];
            }
        }

        $messages = array_merge($first_messages, $history_messages);

        apiReturn(1, '获取数据成功', $messages);
    }

    public function checkUserSendMessageAuth()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $count = Db::name('message')->where(['user_id' => $user_id])->count();
        if ($count < C('FREE_COUNT')) {
            apiReturn(1, '有权限');
        } else {
            apiReturn(2, '免费次数已用完，请拨打电话充值：0731-85505845');
        }
    }

    public function userTextPrompt()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $prompt = $input['prompt'];
        $type = $input['type'] ? : 1;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($prompt)) apiReturn(2, '请输入内容');

        switch ($type) {
            case 1:
                $default_prompt = '我是小红书文案助手，你有什么文案需要我帮你写吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 2:
                $default_prompt = '我可以帮你进行诗词创作，你有什么想法吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 3:
                $default_prompt = '将你需要扩写的句子发给我，我可以帮你进行扩写哦';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 4:
                $default_prompt = '我可以帮你生成标题';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 5:
                $default_prompt = '我可以帮你撰写营销文案，你有什么想法吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 6:
                $default_prompt = '我可以帮你进行朋友圈文案创作，你有什么想法吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 7:
                $default_prompt = '我可以帮你制作方案，你有什么想法吗？';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 8:
                $default_prompt = '我是直播带货剧本生成器，你可以输入你的商品信息，我会帮你生成一段直播带货的剧本。';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
            case 9:
                $default_prompt = '我是短视频脚本生成器，你可以输入你的视频内容，我会帮你生成一段短视频的脚本。';
                $first_messages = [
                    [
                        'role' => 'system',
                        'content' => $default_prompt
                    ]
                ];
                break;
        }

        $list = Db::name('message')->field('id,prompt,text')->where(['user_id' => $user_id, 'type' => $type])->order('id asc')->select();
        $history_messages = [];
        if ($list) {
            foreach ($list as &$v) {
                $history_messages[] = [
                    'role' => 'user',
                    'content' => $v['prompt']
                ];
                $history_messages[] = [
                    'role' => 'assistant',
                    'content' => $v['text']
                ];
            }
        }

        $prompt_messages = [
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ];

        $messages = array_merge($first_messages, $history_messages, $prompt_messages);
        $data = $this->textGeneration($messages);
        if ($data) {
            $text = $data['output']['text'];
            $request_id = $data['request_id'];

            if ($prompt && $text) {
                $insert_data = [
                    'user_id' => $user_id,
                    'prompt' => $prompt,
                    'text' => $text,
                    'request_id' => $request_id,
                    'type' => $type,
                    'create_time' => time()
                ];
                Db::name('message')->insert($insert_data);

                $new_messages = [
                    'role' => 'assistant',
                    'content' => $text
                ];

                apiReturn(1, '获取数据成功', $new_messages);
            } else {
                apiReturn(2, '获取数据失败');
            }
        } else {
            apiReturn(2, '获取数据失败');
        }
    }

    /**
     * 文本智能问答
     * */
    public function textGeneration($messages)
    {
        $url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation';

        $header = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->api_key,
            //            'X-DashScope-SSE' => 'enable'
        ];

        $input = [
            'messages' => $messages
        ];
        $data = [
            'model' => 'qwen1.5-72b-chat',
            'input' => $input
        ];

        $res = $this->httpCurl($url, json_encode($data), $header);
        file_put_contents(RUNTIME_PATH . 'data.txt', $res);
        if ($res !== false) {
            // 处理 API 响应数据
            $responseData = json_decode($res, true);

            return $responseData;
        } else {
            return false;
        }
    }

    /**
     * 接收文本内容，存入redis
     * */
    public function receiveText()
    {
        $input = Request()->param();

        $uid = $input['uid'];
        $text = $input['text'];

        file_put_contents(RUNTIME_PATH . 'receiveText.txt', json_encode($input, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);

        if (empty($uid)) apiReturn(2, '您还未登录，请先登录');
        if (!$text) apiReturn(2, '文本内容为空');

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);

        //        $id = Db::name('msg_chat')->insertGetId(['uid' => $uid, 'text' => $text, 'create_time' => time()]);
        //        if (!$id) apiReturn(2, '接收信息失败');

        $data = [
            'uid' => $uid,
            'text' => $text
        ];
        $redis->rPush('msg', json_encode($data, JSON_UNESCAPED_UNICODE));
        $len = $redis->lLen('msg');
        file_put_contents(RUNTIME_PATH . 'len.txt', $len . PHP_EOL, FILE_APPEND);
        if ($len == 1) {
            file_get_contents(getHost() . '/index/api/aiCallback/is_first/1/text/' . $text);
        }

        apiReturn(1, '接收成功');
    }

    /**
     * 数字人回调通知，接收到通知之后，从redis队列中取出最新一条数据，返回给数字人
     * */
    public function aiCallback()
    {
        $input = Request()->param();

        $is_first = isset($input['is_first']) ? $input['is_first'] : 0;
        $first_text = isset($input['text']) ? $input['text'] : '';
        $del_prev_text = isset($input['del_prev_text']) ? $input['del_prev_text'] : 0;

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);

        if ($del_prev_text == 1) $redis->lPop('msg');

        if ($is_first == 1 && $first_text != '') {
            file_put_contents(RUNTIME_PATH . 'first_callback.txt', $first_text . PHP_EOL, FILE_APPEND);

            $url = 'https://www.tany-ai.com/talk/?ask=' . urlencode($first_text) . '&del_prev_text=1';
            $this->get($url);
        } else {
            $msg = $redis->lPop('msg');
            file_put_contents(RUNTIME_PATH . 'callback.txt', $msg . PHP_EOL, FILE_APPEND);
            if ($msg) {
                $msg = json_decode($msg, true);
                $text = $msg['text'];

                $url = 'https://www.tany-ai.com/talk/?ask=' . urlencode($text);
                $this->get($url);
            }
        }
    }

    public function get($url)
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => "", // 支持 gzip, deflate, br
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
            CURLOPT_HTTPHEADER => [
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
                'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
                'Referer: https://www.tany-ai.com/',
                'Upgrade-Insecure-Requests: 1',
                'Cache-Control: no-cache',
                'Pragma: no-cache'
            ],
        ]);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        echo "状态码：$http_code\n";
        echo "响应内容：\n$response";

    }

    /**
     * 互动数字人界面数据
     * */
    public function getChatData()
    {
//        $input = Request()->param();

//        $user_id = $input['user_id'];
//
//        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
//
//        $list = Db::name('msg_chat')->where(['is_answer' => 0])->order('id asc')->select();
//        if ($list) {
//            foreach ($list as &$v) {
//                $avatar = Db::name('user')->where(['id' => $v['user_id']])->value('avatar');
//                $v['avatar'] = doAvatar($avatar);
//            }
//        }
        $count = rand(2300, 2800);

        $data = [
            'count' => $count
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 上传语音
     * */
    public function uploadVoice()
    {
        if ($_FILES['file']) {
            $dir = './uploads/voice/' . date('Ymd') . '/';
            if (!is_dir($dir)) mkdir($dir, 0777, true);

            $fileName = (time() . '_' . uniqid()) . '_' . basename($_FILES['file']['name']);
            $uploadFile = $dir . $fileName;

            if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
                echo json_encode(['status' => 'success', 'url' => getHost() . substr($uploadFile, 1)]);
            } else {
                echo json_encode(['status' => 'error', 'message' => '上传失败']);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => '上传失败']);
        }
    }

    /**
     * 提交语音
     * */
    public function submitVoice()
    {
        if ($_FILES['file']) {
            $file = $_FILES['file']['tmp_name'];

            $access_token = get_access_token();
            if (!$access_token) apiReturn(2, '获取access_token失败');

            $voice_id = uniqid() . time();

            $curlFile = new \CURLFile($file, 'audio/mp3', 'voice.mp3');

            $url = "https://api.weixin.qq.com/cgi-bin/media/voice/addvoicetorecofortext?access_token=$access_token&format=mp3&voice_id=$voice_id&lang=zh_CN";

            $res = $this->httpPost($url, $curlFile);
            if ($res) {
                $data = json_decode($res, true);
                if ($data['errcode'] == 0) {
                    apiReturn(1, '上传成功', $voice_id);
                }
            } else {
                apiReturn(2, '上传失败');
            }
        } else {
            apiReturn(2, '请上传语音');
        }
    }

    /**
     * 语音识别
     * */
    public function voiceRecognition()
    {
        $input = Request()->param();

        $voice_id = $input['voice_id'];
        if (!$voice_id) apiReturn(2, '语音id为空');

        $access_token = get_access_token();
        if (!$access_token) apiReturn(2, '获取access_token失败');

        $url = "https://api.weixin.qq.com/cgi-bin/media/voice/queryrecoresultfortext?access_token=$access_token&voice_id=$voice_id&lang=zh_CN";
        $res = $this->httpCurl($url);
        if ($res) {
            $data = json_decode($res, true);
            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '获取数据失败');
        }
    }

    // 公共 POST 请求方法
    public function httpPost($url, $postData)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);

        // 使用 multipart/form-data
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ['media' => $postData]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output, true);
    }
}
